package com.example.duanjunjie.learn.wk;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import rx.functions.Func1;

/**
 * Created by xiejinghui on 2017/5/15.
 */

public class WKListenerList<E> {
    private List<WeakReference<E>> listenerList = new ArrayList<>();

    public void add(E listener) {
        iterator().add(new WeakReference<E>(listener));
    }

    public void remove(E listener) {
        ListIterator<WeakReference<E>> ite = iterator();
        while (ite.hasNext()) {
            WeakReference<E> e = ite.next();
            if (e != null) {
                if (e.get() != null) {
                    if (listener == e.get()) {
                        ite.remove();
                    }
                } else {
                    ite.remove();
                }
            } else {
                ite.remove();
            }
        }
    }

    public ListIterator<WeakReference<E>> iterator() {
        return listenerList.listIterator();
    }

    public void invoke(Func1<E, Void> func) {
        ListIterator<WeakReference<E>> ite = iterator();
        while (ite.hasNext()) {
            WeakReference<E> e = ite.next();
            if (e != null) {
                if (e.get() != null) {
                    func.call(e.get());
                } else {
                    ite.remove();
                }
            } else {
                ite.remove();
            }
        }
    }
}
